<template>
  <a-spin :spinning="confirmLoading">
    <a-form-model ref="labelForm" :label-col="labelCol" :model="model" :wrapper-col="wrapperCol">
      <a-form-model-item v-show="false" ref="deviceModelBy" label="模型主键" prop="deviceModelBy">
        <a-input v-model="model.deviceModelBy" readOnly></a-input>
      </a-form-model-item>
      <a-form-model-item v-show="false" ref="id" label="主键" prop="id">
        <a-input v-model="model.id" readOnly></a-input>
      </a-form-model-item>
      <a-form-model-item ref="code" :rules="rules.code" label="标识" prop="code">
        <a-input v-model="model.code" placeholder="请输入标识"></a-input>
      </a-form-model-item>
      <a-form-model-item ref="title" :rules="rules.title" label="标题" prop="title">
        <a-input v-model="model.title" placeholder="请输入名称"></a-input>
      </a-form-model-item>
      <a-form-model-item ref="hideTitle" label="隐藏标题" prop="hideTitle">
        <a-checkbox v-model="model.hideTitle"></a-checkbox>
      </a-form-model-item>
      <a-form-model-item ref="style" :rules="rules.style" label="标签样式" prop="style">
        <j-code-editor v-model="model.style" :fullScreen="true" language="css" style="min-height: 100px"></j-code-editor>
      </a-form-model-item>
      <a-form-model-item ref="viewData" :rules="rules.viewData" :wrapperCol="{ span: '24' }" label="" prop="viewData">
        <a-card :hoverable="true" size="small" title="显示数据">
          <template slot="extra">
            <a-dropdown>
              <a-menu slot="overlay" @click="handleViewDataClick">
                <a-menu-item key="model">模型数据</a-menu-item>
                <a-menu-item key="instance">实例数据</a-menu-item>
                <a-menu-item key="property">数据节点</a-menu-item>
                <a-menu-item key="html">自定义html</a-menu-item>
              </a-menu>
              <a-button> 添加
                <a-icon type="down" />
              </a-button>
            </a-dropdown>
          </template>
          <a-row style="margin-bottom:6px;border-bottom:1px solid #f0f0f0" type="flex">
            <a-col :span="10">
              数据key
            </a-col>
            <a-col :span="6">
              数据名称
            </a-col>
            <a-col :span="6">
              类型
            </a-col>
            <a-col :span="2">操作</a-col>
          </a-row>
          <template v-if="model.viewData.length > 0">
            <a-row v-for="view in model.viewData" :key="view.index" style="margin-bottom:6px;border-bottom:1px solid #f0f0f0">
              <a-col :span="10"
              ><span>{{ view.source }}.{{ view.key }}</span></a-col
              >
              <a-col :span="6">{{ view.name }}</a-col>
              <a-col :span="6">{{ view.type }}</a-col>
              <a-col :span="2">
                <a-icon theme="twoTone" type="delete" @click="handleViewDataDelete(view.key)" />
              </a-col>
            </a-row>
          </template>
        </a-card>

        <device-model-data ref="modelDataModal" @ok="viewDataOk"></device-model-data>
        <device-instance-data ref="instanceDataModal" @ok="viewDataOk"></device-instance-data>
        <device-property-data ref="propertyDataModal" @ok="viewDataOk"></device-property-data>
      </a-form-model-item>
      <a-form-model-item ref="checkbox" :rules="rules.enable" label="是否有效" prop="checkbox">
        <a-checkbox v-model="model.enable" />
      </a-form-model-item>
      <a-form-model-item ref="defaultTrigger" :rules="rules.defaultTrigger" label="触发方式" prop="defaultTrigger">
        <a-select v-model="model.defaultTrigger" placeholder="请选择触发方式">
          <a-select-option v-for="option in defaultTriggerOptions" :key="option.value">{{ option.text }}</a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item ref="closeMethod" :rules="rules.closeMethod" label="关闭方式" prop="closeMethod">
        <a-select v-model="model.closeMethod" placeholder="请选择关闭方式">
          <a-select-option v-for="option in closeMethodOptions" :key="option.value">{{ option.text }}</a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item ref="displayDuration" :rules="rules.displayDuration" label="显示时长" prop="displayDuration">
        <a-input-number v-model="model.displayDuration" placeholder="请输入显示时长" style="width: 100%" />
      </a-form-model-item>
      <a-form-model-item ref="description" label="描述" prop="description">
        <a-textarea v-model="model.description" placeholder="请输入描述" rows="4" />
      </a-form-model-item>
    </a-form-model>
  </a-spin>
</template>

<script>
import { getAction, httpAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
import JDictSelectTag from '@/components/dict/JDictSelectTag'
import JMultiSelectTag from '@/components/dict/JMultiSelectTag'
import JMarkdownEditor from '@/components/jeecg/JMarkdownEditor/index'
import JCodeEditor from '@/components/jeecg/JCodeEditor.vue'
import DeviceModelData from './DeviceModelData.vue'
import DeviceInstanceData from './DeviceInstanceData.vue'
import DevicePropertyData from './DevicePropertyData.vue'

export default {
  name: 'DeviceLabelForm',
  components: {
    JDictSelectTag,
    JMultiSelectTag,
    JMarkdownEditor,
    JCodeEditor,
    DeviceModelData,
    DeviceInstanceData,
    DevicePropertyData
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    deviceModelBy: {
      type: String,
      default: false,
      required: true
    }
  },
  data() {
    return {
      form: this.$form.createForm(this),
      viewDataColumns: [
        {
          title: '数据key',
          dataIndex: 'dataKey'
        },
        {
          title: '数据名称',
          dataIndex: 'dataName',
          scopedSlots: { customRender: 'dataNameSlot' }
        },
        {
          title: '数据类型',
          dataIndex: 'dataType',
          scopedSlots: { customRender: 'dataTypeSlot' }
        }
      ],
      viewDataSources: [],
      model: {
        deviceModelBy: this.deviceModelBy,
        code: '',
        title: '',
        hideTitle: false,
        style: ``,
        viewData: [],
        enable: true,
        defaultTrigger: '',
        displayDuration: 0,
        closeMethod: '',
        description: ''
      },
      defaultTriggerOptions: [],
      closeMethodOptions: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      rules: {
        code: [
          { required: true, message: '请输入实例标识!', trigger: 'change' },
          { min: 3, max: 30, message: '标识长度为3-30个字符', trigger: 'change' },
          {
            validator: (rule, value, callback) => validateDuplicateValue('iot_device_label', 'code', value, this.model.id, callback),
            trigger: 'change'
          }
        ],
        title: [
          { required: true, message: '请输入标题!' },
          { min: 2, max: 30, message: '标题长度为2-30个字符' }
        ],
        viewData: [{ required: true, message: '请添加显示数据!' }],
        defaultTrigger: [{ required: true, message: '请选则触发方式!' },
          { validator: (rule, value, callback) => this.validateDefaultTrigger(rule, value, this.model.id, callback), trigger: 'change' }],
        closeMethod: [{ required: true, message: '请选则关闭方式!' }],
        displayDuration: [{ required: true, message: '请输入显示时长!' }, {
          validator: (rule, value, callback) => {
            if(this.model.closeMethod.indexOf('delay') !== -1){
              if(value < 1) {
                callback(new Error('延时关闭时长至少1秒钟(s)'));
              }
              callback();
            }
            callback();
          },
          trigger: 'change'
        }],
      },
      url: {
        add: '/device/label/add',
        edit: '/device/label/edit',
        queryById: '/device/label/queryById',
        labelTrigger: '/device/label/getLabelTrigger',
        labelCloseMethod: '/device/label/getLabelCloseMethod'
      }
    }
  },
  watch: {},
  computed: {},
  created() {
    this.getLabelTrigger()
    this.getLabelCloseMethod()
  },
  methods: {
    validateDefaultTrigger(rule, value, labelId, callback) {
      getAction("/device/label/validateDuplicateDefaultTrigger", {
        id: labelId,
        deviceModelBy: this.model.deviceModelBy,
        defaultTrigger: value
      }).then(data => {
        if (data.success) {
          if(data.result > 0) {
            callback(new Error('页面加载触发方式已经存在！'))
          }
        }
        callback()
      })
    },
    handleViewDataDelete(key) {
      let scope = this
      for (let i in this.model.viewData) {
        if (this.model.viewData[i].key === key) {
          scope.model.viewData.splice(i, 1)
        }
      }
    },
    viewDataOk(datas) {
      let scope = this
      JSON.parse(JSON.stringify(datas || [])).map(data => {
        // 删除index项
        delete data.index
        // 删除列表中已存在的显示对象
        let i = 0
        for (let i in scope.model.viewData) {
          if (scope.model.viewData[i].source === data.source && scope.model.viewData[i].key === data.key) {
            let name = scope.model.viewData[i].name
            scope.model.viewData.splice(i, 1)
            console.log('删除', i, name)
          }
        }
        this.$nextTick(function() {
          scope.model.viewData.push(data)
          console.log('显示数据', scope.model.viewData)
        })
      })
    },
    getLabelTrigger() {
      let scope = this
      getAction(this.url.labelTrigger).then(data => {
        if (data.success) {
          scope.defaultTriggerOptions = data.result
        }
      })
    },
    getLabelCloseMethod() {
      let scope = this
      getAction(this.url.labelCloseMethod).then(data => {
        if (data.success) {
          scope.closeMethodOptions = data.result
        }
      })
    },
    add() {
      this.edit({})
    },
    edit(record) {
      this.$refs.labelForm.resetFields()
      this.model = Object.assign(this.model, record)
      // this.model.viewData = JSON.parse(this.model.viewData)
      this.visible = true
    },
    handleViewDataClick(item) {
      let scope = this
      switch (item.key) {
        case 'model':
          scope.$refs.modelDataModal.visible = true
          break
        case 'instance':
          scope.$refs.instanceDataModal.visible = true
          break
        case 'property':
          scope.$refs.propertyDataModal.visible = true
          console.log('handleViewDataClick')
          scope.$refs.propertyDataModal.getProperty(scope.deviceModelBy)
          break
        case 'html':
          break
        default:
          break
      }
    },
    handleOk() {
      const scope = this

      // 触发表单验证
      this.$refs.labelForm.validate(valid => {
        console.log('表单提交数据', scope.model)
        if (valid) {
          scope.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }

          let formData = JSON.parse(JSON.stringify(this.model))
          formData.viewData = formData.viewData.map(data => {
            console.log(data.convert)
            if (!data.convert === JSON) data.convert = JSON.parse(data.convert)
            return data
          })
          // formData.viewData = JSON.stringify(formData.viewData)
          console.log('表单提交数据', formData)

          scope.confirmLoading = false

          httpAction(httpurl, formData, method)
            .then(res => {
              if (res.success) {
                scope.$message.success(res.message)
                scope.$emit('ok')
              } else {
                scope.$message.warning(res.message)
              }
            })
            .catch(err => {
              console.error(err)
              scope.confirmLoading = false
            })
            .finally(() => {
              scope.confirmLoading = false
            })
        } else {
          return false
        }
      })
    },
    isJSON(str) {
      if (typeof str == 'string') {
        try {
          var obj = JSON.parse(str)
          if (typeof obj == 'object' && obj) {
            return true
          } else {
            return false
          }
        } catch (e) {
          console.log('error：' + str + '!!!' + e)
          return false
        }
      }
      console.log('It is not a string!')
    }
  }
}
</script>
